package com.znow.admin.system.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.znow.admin.dao.entity.sys.SysUserEntity;
import com.znow.admin.dao.mapper.sys.SysUserMapper;
import com.znow.admin.system.security.model.convert.SysUserConvert;
import com.znow.admin.system.security.model.dto.PermissionsTreeDTO;
import com.znow.admin.system.security.model.dto.SysUserDetailsDTO;
import com.znow.admin.system.security.model.res.user.UserRequest;
import com.znow.admin.system.security.model.res.user.UserPageRequest;
import com.znow.admin.system.security.service.SysPermissionsService;
import com.znow.admin.system.security.service.SysUserService;
import com.znow.common.enums.error.ResultCodeEnums;
import com.znow.common.exception.BizException;
import com.znow.common.exception.ParamsException;
import com.znow.common.model.PageResult;
import com.znow.common.utils.regex.RegexUtils;
import io.jsonwebtoken.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户服务实现类
 *
 * @author Nemo
 * @date 2022/09/29
 */
@Slf4j
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysPermissionsService sysPermissionsService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final SysUserEntity userEntity = sysUserMapper.selectByUsername(username);
        if (userEntity == null) {
            throw new UsernameNotFoundException("用户不存在！");
        }
        final SysUserDetailsDTO userDTO = SysUserConvert.INSTANCE.toUserDTO(userEntity);
        final Long userId = userEntity.getUserId();
        final List<PermissionsTreeDTO> authorities = sysPermissionsService.getPermissionsByUserId(userId);
        userDTO.setAuthorities(authorities);
        return userDTO;
    }

    @Override
    public PageResult<SysUserEntity> selectByPage(UserPageRequest param) {
        final LambdaQueryWrapper<SysUserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserEntity::getIsDel, 0);
        if (StringUtils.isNotBlank(param.getUsername())) {
            queryWrapper.like(SysUserEntity::getUsername, param.getUsername());
        }
        // 不查询用户的密码
        queryWrapper.select(SysUserEntity.class, info -> !info.getColumn().equals("password"));
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        final List<SysUserEntity> sysUserEntities = sysUserMapper.selectList(queryWrapper);
        return PageResult.of(sysUserEntities);
    }

    @Override
    public SysUserEntity getUserId(UserPageRequest param) {
        final SysUserEntity sysUserEntity = sysUserMapper.selectById(param.getUserId());
        if (sysUserEntity == null) {
            throw new BizException(ResultCodeEnums.RESOURCE_NOT_EXIST);
        }
        return sysUserEntity;
    }

    @Override
    public boolean updateUser(UserRequest request) {
        checkSaveOrUpdateParam(false, request);
        LambdaQueryWrapper<SysUserEntity> queryWrapper = new LambdaQueryWrapper<SysUserEntity>()
                .eq(SysUserEntity::getUserId, request.getUserId())
                .eq(SysUserEntity::getIsDel, NumberUtils.INTEGER_ZERO);
        final SysUserEntity query = sysUserMapper.selectOne(queryWrapper);
        if (query == null) {
            throw new BizException(ResultCodeEnums.INVALID_PARAM, "用户不存在");
        }
        SysUserEntity update = SysUserConvert.INSTANCE.convertUserEntityWithAddUserRequest(request);
        update.setUserId(request.getUserId());
        return sysUserMapper.updateById(update) > 0;
    }

    @Override
    public boolean saveUser(UserRequest request) {
        checkSaveOrUpdateParam(true, request);
        SysUserEntity insert = SysUserConvert.INSTANCE.convertUserEntityWithAddUserRequest(request);
        insert.setUserId(null);
        return sysUserMapper.insert(insert) > 0;
    }

    @Override
    public boolean deleteUser(UserPageRequest request) {
        if (request.getUserId() == null) {
            throw new ParamsException("用户ID不能为空！");
        }
        SysUserEntity update = new SysUserEntity();
        update.setUserId(request.getUserId());
        update.setIsDel(NumberUtils.INTEGER_ONE);
        return sysUserMapper.updateById(update) > 0;
    }

    /**
     * 检查保存或更新参数
     *
     * @param type    类型
     * @param request 请求
     */
    public void checkSaveOrUpdateParam(boolean type, UserRequest request) {
        Assert.notNull(request, ResultCodeEnums.INVALID_PARAM.getMessage());
        if (!type) {
            if (request.getUserId() == null) {
                throw new ParamsException("用户ID不能为空！");
            }
        }
        if (request.getUsername() == null) {
            throw new ParamsException("用户名称不能为空！");
        }
        if (StringUtils.isBlank(request.getPhone())) {
            throw new ParamsException("手机号不能为空！");
        }
        if (!RegexUtils.isMobileSimple(request.getPhone())) {
            throw new ParamsException("手机号格式不正确！");
        }
        if (request.getEmail() == null) {
            throw new ParamsException("邮箱不能为空！");
        }
        if (!RegexUtils.isEmail(request.getEmail())) {
            throw new ParamsException("邮箱格式错误！");
        }
    }
}
